Easy2Siksha.com
GNDU QUESTION PAPERS 2024
Bachelor of Computer Applicaon (BCA) 2nd Semester
(Batch 2023-26) (CBGS)
INTRODUCTION TO PROGRAMMING-C++
Time Allowed: 3 Hours Maximum Marks: 75
Note: Aempt Five quesons in all, selecng at least One queson from each secon. The
Fih queson may be aempted from any secon. All quesons carry equal marks.
SECTION-A
1. What is meant by tradional Programming? What are the pros and cons of using it ?
2. What is the importance of messaging and abstracon?
SECTION-B
3. Explain the importance of destructor using C++ code.
4. What are the types of constructors in C++?
SECTION-C
5. What is meant by ambiguity in funcon overloading"
6. Explain overloading of a funcon of your choice.
Easy2Siksha.com
SECTION-D
7. How do we classify classes based on Inheritance ? Explain with examples using C++
code.
8. Explain the use of template using C++ code.
GNDU ANSWER PAPERS 2024
Bachelor of Computer Applicaon (BCA) 2nd Semester
(Batch 2023-26) (CBGS)
INTRODUCTION TO PROGRAMMING-C++
Time Allowed: 3 Hours Maximum Marks: 75
Note: Aempt Five quesons in all, selecng at least One queson from each secon. The
Fih queson may be aempted from any secon. All quesons carry equal marks.
SECTION-A
1. What is meant by tradional Programming? What are the pros and cons of using it ?
Ans: Imagine you are giving instructions to a robot. You tell it step by step exactly what to
dofirst do this, then do that, and finally give the result. This is exactly what traditional
programming is.
In traditional programming, a human (the programmer) writes a set of clear instructions
(called code) that tells the computer how to perform a task. The computer simply follows
these instructions line by line without thinking or learning on its own.
For example, if you want a program to calculate the sum of two numbers, you write the
exact steps:
1. Take two numbers as input
Easy2Siksha.com
2. Add them
3. Display the result
The computer does not “understand” anything—it just follows your instructions.
So, in simple words:
󷷑󷷒󷷓󷷔 Traditional programming = Human writes rules → Computer follows them → Output is
produced
Key Features of Traditional Programming
It is rule-based (everything depends on predefined instructions)
It is deterministic (same input always gives the same output)
It does not learn from experience
The logic is fully controlled by the programmer
Languages like C, C++, Java, and Python (when used normally) are examples of traditional
programming.
Pros (Advantages) of Traditional Programming
Let’s understand the benefits in a very practical way:
1. Easy to Control
Since you write every instruction, you have full control over the program. Nothing happens
automatically.
󷷑󷷒󷷓󷷔 Example: In a banking app, you can control exactly how interest is calculated.
2. Predictable Results
Traditional programs always give the same output for the same input.
󷷑󷷒󷷓󷷔 Example: 2 + 2 will always be 4, no surprises.
This makes it reliable and safe for critical systems.
3. Easier to Debug
Easy2Siksha.com
If something goes wrong, you can trace the exact step where the error occurred because
everything is written clearly.
󷷑󷷒󷷓󷷔 Example: If a calculator gives a wrong answer, you can check the formula used.
4. No Need for Large Data
Unlike modern AI systems, traditional programming does not require huge datasets to work.
󷷑󷷒󷷓󷷔 You just need logic, not training data.
5. Efficient for Simple Problems
For straightforward tasks (like calculations, sorting, or basic apps), traditional programming
is fast and efficient.
Cons (Disadvantages) of Traditional Programming
Now let’s look at the limitations, which are equally important:
1. Cannot Learn or Adapt
Traditional programs cannot improve themselves. They only do what they are told.
󷷑󷷒󷷓󷷔 Example: A spam filter written traditionally cannot automatically learn new spam
patterns.
2. Difficult for Complex Problems
Some problems are too complex to define with clear rules.
󷷑󷷒󷷓󷷔 Example:
Recognizing faces
Understanding human language
Predicting weather
These tasks require learning, not fixed instructions.
Easy2Siksha.com
3. Time-Consuming to Write Rules
For complex systems, writing every rule manually becomes very difficult and time-
consuming.
󷷑󷷒󷷓󷷔 Imagine writing rules for all possible traffic situations in a self-driving car—it’s nearly
impossible!
4. Lack of Flexibility
If conditions change, the program must be updated manually.
󷷑󷷒󷷓󷷔 Example: If tax rules change, you must rewrite the code.
5. Human Dependency
Everything depends on the programmer’s thinking. If the programmer misses something,
the program will fail.
Final Understanding
Think of traditional programming like a recipe book:
The chef (computer) follows the recipe exactly
The recipe (code) is written by a human
No creativity, no learningjust instructions
This makes it perfect for tasks where:
Rules are clear
Results must be exact
No learning is needed
But it struggles when:
󽆱 Problems are complex
󽆱 Learning and adaptation are required
Conclusion
Easy2Siksha.com
Traditional programming is the foundation of computer science. It is simple, reliable, and
powerful for many tasks. However, in today’s world—where problems are complex and
dynamicit is often combined with modern approaches like machine learning.
In short:
󷷑󷷒󷷓󷷔 Traditional programming is like telling a computer exactly “what to do,” step by step
no more, no less.
2. What is the importance of messaging and abstracon?
Ans: Picture yourself texting a friend. You don’t write out every detail of your hunger or the
science behind digestion. You just say: “Let’s grab pizza.” That’s messaging—short, clear
communication. And it’s also abstraction—you’re hiding all the unnecessary details and
focusing on the main idea. Your friend instantly understands.
󹳾󹳿󹴀󹴁󹴂󹴃 Computers and Complexity
Computers are incredibly detailed machines. They run on billions of ones and zeros every
second. If humans had to deal with that raw detail, programming would be impossible.
That’s why abstraction exists—it hides the messy details and gives us a simpler way to
interact with complex systems.
When you click “Send” on WhatsApp, you don’t need to know how your message is broken
into packets, routed through servers, and reassembled on your friend’s phone. All of that is
abstracted away.
Messaging, on the other hand, is how different parts of a system talk to each other. One
program might send a message to another saying, “Task completed,” or “I need this data.”
Just like you send a text to a friend.
󹷗󹷘󹷙󹷚󹷛󹷜 Messaging in Action
Think of a company with different departments: sales, marketing, and customer support.
Each department has its own job, but they need to talk to each other. If sales gets a new
client, they send a message to marketing: “Prepare a campaign.” Marketing doesn’t need to
know every detail about how sales closed the dealthey just need the message.
Computers work the same way:
Messaging allows different parts of a system to coordinate without interfering with
each other’s internal details.
It makes systems more flexibleyou can swap out one part without breaking
everything else, as long as the messages stay consistent.
Easy2Siksha.com
It supports scalabilitysystems can grow bigger and more complex, but still
communicate smoothly through messages.
󷘧󷘨 Abstraction in Action
Back to the pizza example. Abstraction is what lets you say “pizza” instead of listing every
ingredient. In computing:
Abstraction lets programmers work at a higher level. Instead of writing raw machine
code, they use languages like Python or Java.
It makes learning easier. You don’t need to know how memory chips are wired to
write a programyou just use variables and functions.
It encourages creativity. By hiding complexity, abstraction frees your mind to focus
on solving problems, not drowning in details.
󼩺󼩻 Messaging + Abstraction Together
Here’s where the magic happens: messaging and abstraction work hand in hand.
Messaging is about communication.
Abstraction is about simplicity.
Together, they make systems understandable, manageable, and efficient. Imagine building a
huge Lego city. Each Lego block is an abstractionit represents something simple.
Messaging is how those blocks connect and interact. Without abstraction, you’d be stuck
carving tiny bricks out of stone. Without messaging, your Lego blocks would just sit there,
never forming a city.
󺛺󺛻󺛿󺜀󺛼󺛽󺛾 Real-World Examples
1. Social Media Apps When you post a photo, the app sends a message to the server:
“Upload this image.” You don’t see the technical details—compression, storage,
retrieval. That’s abstraction at work.
2. Operating Systems When you click “Print,” your computer sends a message to the
printer driver. You don’t need to know how the printer translates dots of ink onto
paper. Abstraction hides it, messaging delivers the request.
3. Teamwork in School Projects If you’re working on a group project, each person
abstracts their part (research, slides, design). You don’t micromanage each other’s
workyou just send messages like: “I’ll finish the slides by tomorrow.” That’s exactly
how software components collaborate.
󷈷󷈸󷈹󷈺󷈻󷈼 For Students
Understanding messaging and abstraction isn’t just about computers—it’s about life skills
too. Messaging teaches you to communicate clearly. Abstraction shows you the power of
simplifying complexity. Together, they help you see how big systemswhether human
organizations or digital networksstay organized.
Easy2Siksha.com
SECTION-B
3. Explain the importance of destructor using C++ code.
Ans: 󷊆󷊇 What is a Destructor?
In C++, a destructor is a special member function of a class that is automatically called when
an object goes out of scope or is destroyed.
Think of it like this:
󷷑󷷒󷷓󷷔 A constructor is used to create and initialize an object.
󷷑󷷒󷷓󷷔 A destructor is used to clean up before the object is removed from memory.
It’s like renting a room:
When you enter → you set things up (constructor)
When you leave → you clean everything (destructor)
󼩏󼩐󼩑 Why is Destructor Important?
Imagine you are working with resources like:
Memory (using new)
Files
Database connections
If you don’t release these resources properly, your program may:
Waste memory
Crash
Slow down over time
󷷑󷷒󷷓󷷔 This is where destructors help. They ensure proper cleanup automatically.
󷘹󷘴󷘵󷘶󷘷󷘸 Key Features of Destructor
Same name as the class
Starts with a tilde ~
No return type (not even void)
Automatically called when object is destroyed
Cannot take parameters
Easy2Siksha.com
󹳾󹳿󹴀󹴁󹴂󹴃 Simple C++ Code Example
Let’s understand this with a basic example:
#include <iostream>
using namespace std;
class Demo {
public:
// Constructor
Demo() {
cout << "Constructor called! Object created." << endl;
}
// Destructor
~Demo() {
cout << "Destructor called! Object destroyed." <<
endl;
}
};
int main() {
Demo obj; // Object created
cout << "Inside main function." << endl;
return 0; // Object goes out of scope here
}
󹺔󹺒󹺓 Output
Constructor called! Object created.
Inside main function.
Destructor called! Object destroyed.
󼩺󼩻 Explanation of the Code
1. When obj is created:
o Constructor runs → prints message
2. Program executes normally
3. When main() ends:
o Object obj is destroyed automatically
o Destructor runs → prints message
󷷑󷷒󷷓󷷔 You didn’t call the destructor manually—it happens automatically!
Easy2Siksha.com
󽁔󽁕󽁖 Real Importance (With Dynamic Memory)
Now let’s see a more practical example where destructors are very important.
#include <iostream>
using namespace std;
class Test {
int *ptr;
public:
// Constructor
Test() {
ptr = new int; // dynamically allocate memory
*ptr = 100;
cout << "Memory allocated!" << endl;
}
// Destructor
~Test() {
delete ptr; // free memory
cout << "Memory deallocated!" << endl;
}
};
int main() {
Test obj;
return 0;
}
󼩏󼩐󼩑 What’s Happening Here?
new int allocates memory from heap
If we don’t free it → memory leak
󷷑󷷒󷷓󷷔 Destructor ensures:
delete ptr is called automatically
Memory is safely released
󺡠󺡡󺡢󺡣󺡤󺡥 What Happens Without Destructor?
If we remove the destructor:
Memory allocated using new is never freed
This leads to memory leaks
Easy2Siksha.com
Over time, program performance degrades
󷘹󷘴󷘵󷘶󷘷󷘸 Real-Life Analogy
Think of destructors like:
Turning off lights before leaving a room
Closing apps before shutting down a phone
Returning borrowed books
If you don’t do these:
Resources get wasted
System becomes inefficient
󹵙󹵚󹵛󹵜 Types of Situations Where Destructor is Useful
1. Freeing dynamic memory (new/delete)
2. Closing files
3. Releasing network connections
4. Cleaning up resources in large programs
󹲉󹲊󹲋󹲌󹲍 Important Notes
Only one destructor per class
It cannot be overloaded
Called in reverse order of object creation (for multiple objects)
󷚚󷚜󷚛 Conclusion
The destructor is a powerful feature in C++ that ensures your program remains clean,
efficient, and error-free. While constructors help you set up an object, destructors make
sure everything is properly cleaned up when the object is no longer needed.
In simple words:
󷷑󷷒󷷓󷷔 Constructor = Start of life of object
󷷑󷷒󷷓󷷔 Destructor = End of life of object (cleanup time)
Easy2Siksha.com
Understanding destructors is essential, especially when working with memory and
resources. Once you master this concept, you’ll write safer and more professional C++
programs.
4. What are the types of constructors in C++?
Ans: 󷩆󷩇󷩈󷩉󷩌󷩊󷩋 First, What Is a Constructor?
Imagine you’re building a house. Before anyone can live in it, you need to set up the basics:
walls, doors, windows, electricity. In C++, when you create an object (like a “house”), you
need to set up its initial stategive it values, prepare it for use. That’s what a constructor
does.
A constructor is a special function inside a class that automatically runs when you create an
object. Its job is to “construct” the object, giving it a starting point. You don’t call it
manually—it’s triggered the moment you say something like:
cpp
Car myCar;
Here, Car is a class, and the constructor makes sure myCar is ready to use.
󼩺󼩻 Types of Constructors in C++
Now, constructors come in different flavors, each serving a slightly different purpose. Let’s
walk through them one by one, using relatable examples.
1. Default Constructor
This is the simplest type. It’s like moving into a house where everything is already set up
with standard valueslights work, doors are unlocked, furniture is basic.
In C++, a default constructor is one that takes no arguments. It initializes objects with
default values.
Example:
class Car {
public:
Car() {
speed = 0;
fuel = 100;
}
private:
int speed;
int fuel;
};
Easy2Siksha.com
When you write:
cpp
Car myCar;
The default constructor sets speed = 0 and fuel = 100. You didn’t provide any details, but the
car is ready to go with defaults.
2. Parameterized Constructor
Now imagine you’re buying a car and you want to customize it: color red, speed 50, fuel 80.
That’s where a parameterized constructor comes in. It lets you pass values when creating
the object.
Example:
class Car {
public:
Car(int s, int f) {
speed = s;
fuel = f;
}
private:
int speed;
int fuel;
};
When you write:
cpp
Car myCar(50, 80);
The constructor uses your inputs: speed = 50, fuel = 80. It’s like ordering a pizza with your
choice of toppings instead of accepting the default plain cheese.
3. Copy Constructor
This one is about cloning. Imagine you already have a car, and you want another car exactly
like itsame speed, same fuel. Instead of setting everything again, you just copy the
existing one.
A copy constructor creates a new object by copying values from an existing object.
Example:
cpp
class Car {
public:
Car(const Car &c) {
Easy2Siksha.com
speed = c.speed;
fuel = c.fuel;
}
private:
int speed;
int fuel;
};
When you write:
cpp
Car car1(60, 90);
Car car2(car1);
car2 is now a copy of car1. It’s like photocopying a document—you get the same content
without rewriting it.
4. Dynamic Constructor
This one is a bit more advanced. Imagine you’re renting a house, and the furniture is not
fixedyou can decide how much space you want and bring in your own furniture. A
dynamic constructor allocates memory at runtime using new.
Example:
cpp
class Student {
public:
Student(int n) {
marks = new int[n]; // dynamic memory allocation
size = n;
}
~Student() {
delete[] marks; // free memory
}
private:
int* marks;
int size;
};
Here, the constructor creates space for n marks when the object is made. It’s flexible—you
decide the size when you create the object.
5. Conversion Constructor
This one is about transforming one type into another. Imagine converting dollars into
rupees when you travel. A conversion constructor allows you to create an object from a
different data type.
Easy2Siksha.com
Example:
cpp
class Distance {
public:
Distance(int meters) {
km = meters / 1000.0;
}
private:
double km;
};
When you write:
cpp
Distance d(5000);
It converts 5000 meters into 5 kilometers. That’s a conversion constructor at work.
󷘧󷘨 Why So Many Types?
Each type of constructor solves a different problem:
Default: gives you a ready-to-use object with standard values.
Parameterized: lets you customize your object at creation.
Copy: makes duplicates easily.
Dynamic: allows flexible memory allocation.
Conversion: transforms one type into another.
Together, they make C++ powerful and adaptable, just like how different tools in a toolbox
serve different purposes.
󹶓󹶔󹶕󹶖󹶗󹶘 A Relatable Story
Imagine you’re starting a new school year. You get a “default” backpack with basic supplies.
If you want to personalize it, you buy a “parameterized” backpack with your chosen items. If
your friend has a cool backpack and you want the same, you get a “copy.” If you decide to
add extra pockets later, that’s “dynamic.” And if you convert your old sports bag into a
school bag, that’s “conversion.”
See how constructors are just like everyday choices? They’re about setting things up in the
way you need them.
Easy2Siksha.com
SECTION-C
5. What is meant by ambiguity in funcon overloading"?
Ans: 󷈷󷈸󷈹󷈺󷈻󷈼 Imagine a Real-Life Situation
Think of a teacher in a classroom named “Sir”. Many students call out “Sir!” at the same
time. Now, if two students speak at once and the teacher cannot tell who is calling him, he
gets confused.
This confusion is exactly what we call ambiguity in function overloading.
󹲉󹲊󹲋󹲌󹲍 What is Ambiguity?
Ambiguity in function overloading happens when the compiler cannot decide which
function to call because multiple overloaded functions match the function call equally
well.
In simple words:
󷷑󷷒󷷓󷷔 When the system gets confused between two or more functions, it results in ambiguity.
󼩏󼩐󼩑 Let’s Understand with an Example
Consider this C++ example:
#include <iostream>
using namespace std;
void fun(int a) {
cout << "Integer function";
}
void fun(double a) {
cout << "Double function";
}
int main() {
fun(10.5);
return 0;
}
Here, when we call fun(10.5), the compiler clearly understands that 10.5 is a double, so it
calls the fun(double a) function. No confusion here.
Easy2Siksha.com
󽁔󽁕󽁖 Now See Where Ambiguity Happens
#include <iostream>
using namespace std;
void fun(int a, float b) {
cout << "Function 1";
}
void fun(float a, int b) {
cout << "Function 2";
}
int main() {
fun(10, 10);
return 0;
}
Here’s the problem:
fun(int, float) → matches (10, 10) → second 10 can be converted to float
fun(float, int) → also matches (10, 10) → first 10 can be converted to float
Now the compiler gets confused 󺽈󺽒󺽓󺽉󺽊󺽋󺽌󺽍󺽎󺽏󺽐󺽑󺽔󺽕󺽖
󷷑󷷒󷷓󷷔 It cannot decide which function is better.
󷷑󷷒󷷓󷷔 Both seem equally correct.
This situation is called ambiguity in function overloading.
󹺔󹺒󹺓 Why Does Ambiguity Occur?
Ambiguity usually happens due to:
1. Type Conversion
o When arguments can be converted into multiple types.
o Example: int → float, float → double, etc.
2. Default Arguments
o Sometimes functions have default values, which create confusion.
void fun(int a);
void fun(int a, int b = 10);
fun(5); // Ambiguous!
3. Similar Function Signatures
Easy2Siksha.com
o When two functions differ very slightly, making it hard for the compiler to
choose.
󷘹󷘴󷘵󷘶󷘷󷘸 Key Point to Remember
󷷑󷷒󷷓󷷔 The compiler always tries to find the best match for a function call.
󷷑󷷒󷷓󷷔 If it finds more than one equally good match, it throws an ambiguity error.
󺬣󺬡󺬢󺬤 How to Avoid Ambiguity?
Here are some simple ways:
󽆤 Use clearly different parameter types
󽆤 Avoid unnecessary type conversions
󽆤 Be careful with default arguments
󽆤 Use type casting when needed
Example:
fun(10, 10.0); // Now clear → calls (int, float)
󹵙󹵚󹵛󹵜 Simple Definition (For Exams)
Ambiguity in function overloading is a situation where the compiler is unable to decide
which overloaded function to call because more than one function matches the function
call equally well.
󷔬󷔭󷔮󷔯󷔰󷔱󷔴󷔵󷔶󷔷󷔲󷔳󷔸 Final Understanding
Think of function overloading as giving multiple options to the compiler.
But if you give too many similar options, the compiler gets confusedjust like a teacher
hearing multiple students at once.
So, ambiguity is simply:
󷷑󷷒󷷓󷷔 Confusion due to multiple valid choices
Easy2Siksha.com
6. Explain overloading of a funcon of your choice.
Ans: Imagine you’re at a restaurant. You call the waiter and say, “Bring me food.” Now,
depending on what you mean, the waiter might bring you pizza, pasta, or a salad. The word
“food” is the same, but the actual dish depends on the situation.
In C++, function overloading works the same way. You can have multiple functions with the
same name, but they behave differently depending on the parameters you give them. The
compiler decides which version of the function to run based on the arguments you pass.
󼩺󼩻 Why Do We Need It?
Without overloading, you’d have to create different function names for similar tasks. For
example:
addInt(int a, int b);
addDouble(double a, double b);
addString(string a, string b);
That’s messy. Instead, with overloading, you can just call add() and let the compiler figure
out which version to use. It makes code cleaner, easier to read, and more intuitive.
󷍅󷍆󷍇󷍈󷍉 Choosing an Example: The “Add” Function
Let’s use the add function as our example. Adding is something we do all the timeadding
numbers, adding fractions, even adding strings (like joining words together). So it’s a perfect
candidate to show how overloading works.
1. Adding Integers
cpp
int add(int a, int b) {
return a + b;
}
If you call:
cpp
cout << add(3, 5);
It prints 8. Simple addition of integers.
2. Adding Doubles
cpp
double add(double a, double b) {
return a + b;
}
Easy2Siksha.com
If you call:
cpp
cout << add(3.2, 4.5);
It prints 7.7. Same function name, but now it works with doubles.
3. Adding Strings
cpp
string add(string a, string b) {
return a + b;
}
If you call:
cpp
cout << add("Hello, ", "World!");
It prints Hello, World!. Here, add joins two strings together.
󷘧󷘨 How Does the Compiler Know?
You might wonder: “If all the functions are named add, how does the computer know which
one to use?”
The answer is: the parameters. The compiler looks at the arguments you pass:
If you pass integers, it calls the integer version.
If you pass doubles, it calls the double version.
If you pass strings, it calls the string version.
This process is called compile-time polymorphismthe decision is made when the program
is compiled, not while it’s running.
󹶓󹶔󹶕󹶖󹶗󹶘 A Relatable Story
Think of your smartphone. You press the same “call” button, but depending on what you
select, it might:
Call a phone number.
Call a saved contact.
Call through WhatsApp.
The button is the same, but the action depends on the input. That’s exactly how function
overloading worksthe same name, different behaviors based on context.
󼩏󼩐󼩑 Benefits of Function Overloading
Easy2Siksha.com
1. Readability: You don’t need to remember multiple function names. Just one name
does the job.
2. Flexibility: You can handle different data types with the same function.
3. Organization: Code looks neat and logical.
4. Reusability: You can extend functionality easily without rewriting everything.
󺛺󺛻󺛿󺜀󺛼󺛽󺛾 More Advanced Twist: Different Number of Parameters
Overloading isn’t just about different data types—it can also be about different numbers of
parameters.
Example:
cpp
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
Now:
cpp
cout << add(2, 3); // prints 5
cout << add(2, 3, 4); // prints 9
Same function name, but one version adds two numbers, and the other adds three. It’s like
ordering pizza: sometimes you want two toppings, sometimes three. The restaurant
(compiler) knows which recipe to use.
󼩺󼩻 Rules of Overloading
Functions must differ in parameter type or number of parameters.
You cannot overload just by changing the return type. For example:
cpp
int add(int a, int b);
double add(int a, int b);
This won’t work, because the compiler wouldn’t know which one to choose when you call
add(3, 4).
󷫧󷫨󷫩󷫪󷫫󷫬󷫮󷫭 Classroom Analogy
Easy2Siksha.com
Imagine a teacher named “Mr. Sharma.” Students call him “Sir.” But depending on the
situation:
If you ask him about math, he explains equations.
If you ask him about history, he tells you stories.
If you ask him about sports, he talks about cricket.
Same name, different responses depending on what you ask. That’s function overloading in
human terms.
󼩼󼩽󼩾󼪀󼩿 Practice Exercise
Try writing a multiply() function in C++ that:
1. Multiplies two integers.
2. Multiplies two doubles.
3. Multiplies three integers.
This will help you see how overloading works in practice.
󹵙󹵚󹵛󹵜 Conclusion
Function overloading in C++ is like giving one name to multiple tasks, and letting the
compiler figure out which one you mean based on the inputs. It makes code cleaner, easier
to understand, and more flexible. By overloading functions like add(), you can handle
integers, doubles, strings, or even different numbers of parametersall with the same
name.
SECTION-D
7. How do we classify classes based on Inheritance ? Explain with examples using C++
code.
Ans: When we talk about inheritance in C++, think of it like a family system. Just like
children inherit qualities (like eye color or habits) from their parents, in programming, a
class can inherit properties and functions from another class. This helps us reuse code,
reduce repetition, and make programs more organized.
Now, based on how inheritance happens, we can classify classes into different types of
inheritance. Let’s understand each type in a simple and engaging way with examples.
󷈷󷈸󷈹󷈺󷈻󷈼 1. Single Inheritance
Easy2Siksha.com
This is the simplest form of inheritance.
󷷑󷷒󷷓󷷔 Meaning: One derived (child) class inherits from one base (parent) class.
󼩏󼩐󼩑 Real-life example:
A Car is a type of Vehicle.
󹳾󹳿󹴀󹴁󹴂󹴃 C++ Example:
#include <iostream>
using namespace std;
class Vehicle {
public:
void show() {
cout << "This is a vehicle" << endl;
}
};
class Car : public Vehicle {
};
int main() {
Car c;
c.show();
return 0;
}
󷷑󷷒󷷓󷷔 Here, Car inherits from Vehicle, so it can use the show() function.
󷈷󷈸󷈹󷈺󷈻󷈼 2. Multiple Inheritance
󷷑󷷒󷷓󷷔 Meaning: One derived class inherits from more than one base class.
󼩏󼩐󼩑 Real-life example:
A Smartphone can be both a Camera and a Computer.
󹳾󹳿󹴀󹴁󹴂󹴃 C++ Example:
#include <iostream>
using namespace std;
class Camera {
public:
void click() {
Easy2Siksha.com
cout << "Taking photo" << endl;
}
};
class Computer {
public:
void compute() {
cout << "Computing data" << endl;
}
};
class Smartphone : public Camera, public Computer {
};
int main() {
Smartphone s;
s.click();
s.compute();
return 0;
}
󷷑󷷒󷷓󷷔 Here, Smartphone inherits features from both Camera and Computer.
󷈷󷈸󷈹󷈺󷈻󷈼 3. Multilevel Inheritance
󷷑󷷒󷷓󷷔 Meaning: A class is derived from another derived class.
󼩏󼩐󼩑 Real-life example:
Grandparent → Parent → Child
󹳾󹳿󹴀󹴁󹴂󹴃 C++ Example:
#include <iostream>
using namespace std;
class Animal {
public:
void eat() {
cout << "Eating..." << endl;
}
};
class Dog : public Animal {
public:
void bark() {
cout << "Barking..." << endl;
Easy2Siksha.com
}
};
class Puppy : public Dog {
public:
void weep() {
cout << "Weeping..." << endl;
}
};
int main() {
Puppy p;
p.eat();
p.bark();
p.weep();
return 0;
}
󷷑󷷒󷷓󷷔 Puppy inherits from Dog, and Dog inherits from Animal.
󷈷󷈸󷈹󷈺󷈻󷈼 4. Hierarchical Inheritance
󷷑󷷒󷷓󷷔 Meaning: Multiple derived classes inherit from a single base class.
󼩏󼩐󼩑 Real-life example:
One parent, multiple children.
󹳾󹳿󹴀󹴁󹴂󹴃 C++ Example:
#include <iostream>
using namespace std;
class Shape {
public:
void display() {
cout << "This is a shape" << endl;
}
};
class Circle : public Shape {
};
class Rectangle : public Shape {
};
int main() {
Easy2Siksha.com
Circle c;
Rectangle r;
c.display();
r.display();
return 0;
}
󷷑󷷒󷷓󷷔 Both Circle and Rectangle inherit from Shape.
󷈷󷈸󷈹󷈺󷈻󷈼 5. Hybrid Inheritance
󷷑󷷒󷷓󷷔 Meaning: A combination of two or more types of inheritance.
󼩏󼩐󼩑 Real-life example:
A system that combines family tree structures.
󹳾󹳿󹴀󹴁󹴂󹴃 C++ Example:
#include <iostream>
using namespace std;
class A {
public:
void showA() {
cout << "Class A" << endl;
}
};
class B : public A {
};
class C {
public:
void showC() {
cout << "Class C" << endl;
}
};
class D : public B, public C {
};
int main() {
D d;
d.showA();
d.showC();
Easy2Siksha.com
return 0;
}
󷷑󷷒󷷓󷷔 D inherits from both B and C, and B already inherits from A.
󷘹󷘴󷘵󷘶󷘷󷘸 Summary (Easy Revision)
Type of Inheritance
Description
Single
One parent → One child
Multiple
Many parents → One child
Multilevel
Chain (A → B → C)
Hierarchical
One parent → Many children
Hybrid
Mix of multiple types
8. Explain the use of template using C++ code.
Ans: Imagine you’re cooking pasta. You have a recipe that says: “Boil water, add pasta, cook
for 10 minutes.” Now, whether you’re cooking spaghetti, penne, or macaroni, the steps are
the same—you don’t need a new recipe for each type of pasta.
In programming, templates work the same way. A template is like a general recipe that can
be applied to different data types. Instead of writing separate functions for integers,
doubles, or strings, you write one template function, and the compiler adapts it for
whatever type you use.
󼩺󼩻 What Is a Template in C++?
A template in C++ is a feature that allows you to write generic code. It means you can define
a function or a class without specifying the exact data type. Later, when you use it, the
compiler generates the specific version you need.
Think of it as a “blueprint” that can be reused for different types.
󹷗󹷘󹷙󹷚󹷛󹷜 Why Do We Need Templates?
Without templates, you’d have to write multiple versions of the same function or class. For
example, if you want a function to find the maximum of two numbers, you’d need:
int maxInt(int a, int b) { return (a > b) ? a : b; }
double maxDouble(double a, double b) { return (a > b) ? a : b;
}
char maxChar(char a, char b) { return (a > b) ? a : b; }
Easy2Siksha.com
That’s repetitive and messy. Templates solve this problem by letting you write one generic
function.
󹍬󼍁󼍂󹍮󸁗󼍃󼍄󼍅󼍆󼍇󼍈󼍉󻞶󼍊󹍯󹍰󸢻󼍋󸢼󸢽󼍌󼍍󼍎 Example: Function Template
Here’s how you can write a template for the max function:
#include <iostream>
using namespace std;
template <typename T>
T myMax(T a, T b) {
return (a > b) ? a : b;
}
int main() {
cout << myMax(3, 7) << endl; // works with int
cout << myMax(3.5, 2.1) << endl; // works with double
cout << myMax('a', 'z') << endl; // works with char
return 0;
}
Here:
template <typename T> tells the compiler this is a template with a type parameter T.
T can be replaced with any data type when the function is called.
The same function works for integers, doubles, and characters.
It’s like saying: “I don’t care what type of pasta you’re cooking, the recipe works for all.”
󷩆󷩇󷩈󷩉󷩌󷩊󷩋 Example: Class Template
Templates aren’t just for functions—they can be used for classes too. Imagine you want to
create a stack (like a pile of books). You might want a stack of integers, a stack of doubles, or
a stack of strings. Instead of writing separate classes, you can write one template class.
#include <iostream>
using namespace std;
template <class T>
class Stack {
private:
T arr[100];
int top;
public:
Stack() { top = -1; }
void push(T x) { arr[++top] = x; }
T pop() { return arr[top--]; }
};
Easy2Siksha.com
int main() {
Stack<int> intStack;
intStack.push(10);
intStack.push(20);
cout << intStack.pop() << endl; // prints 20
Stack<string> stringStack;
stringStack.push("Hello");
stringStack.push("World");
cout << stringStack.pop() << endl; // prints World
return 0;
}
Here:
template <class T> makes the stack generic.
You can create Stack<int> or Stack<string> depending on your need.
The same blueprint works for different types of data.
󷘧󷘨 How Templates Work Behind the Scenes
When you call myMax(3, 7), the compiler generates a version of myMax specifically for
integers. When you call myMax(3.5, 2.1), it generates a version for doubles. This process is
called instantiation.
So, templates aren’t magic—they’re instructions to the compiler to create type-specific
versions when needed.
󺛺󺛻󺛿󺜀󺛼󺛽󺛾 Advantages of Templates
1. Code Reusability: Write once, use for many types.
2. Type Safety: Unlike older approaches (like void pointers), templates keep type
checking intact.
3. Cleaner Code: No need to write multiple versions of the same function.
4. Flexibility: Works for both functions and classes.
󼩏󼩐󼩑 Practice Exercise
Try writing a template function swapValues() that swaps two variables. Test it with integers,
doubles, and strings. You’ll see how one function can handle all these cases without
rewriting.
󹵙󹵚󹵛󹵜 Conclusion
Templates in C++ are a powerful way to write generic, reusable, and type-safe code. They
allow you to define a single function or class that works with different data types, saving
time and reducing redundancy. Whether it’s finding the maximum of two numbers, creating
Easy2Siksha.com
a stack, or swapping values, templates let you focus on the logic instead of worrying about
data types.
In essence, templates are about flexibility and efficiency. They give programmers the
freedom to write one blueprint and apply it to many situations, just like a universal recipe
that works for different dishes. That’s why templates are considered one of the
cornerstones of modern C++ programming.
This paper has been carefully prepared for educaonal purposes. If you noce any
mistakes or have suggesons, feel free to share your feedback.